package com.qdlc.p2p.biz.service.impl;

import java.util.Date;

import javax.annotation.Resource;

import org.apache.commons.httpclient.NameValuePair;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;
import com.qdlc.p2p.biz.service.BaseGiveAwardService;
import com.qdlc.p2p.common.util.DateUtil;
import com.qdlc.p2p.common.util.OrderNoUtil;
import com.qdlc.p2p.dal.common.SystemConfigHelper;
import com.qdlc.p2p.dal.dao.AdditionalMovieTicketRuleDao;
import com.qdlc.p2p.dal.dao.AdditionalUserMovieTicketDao;
import com.qdlc.p2p.dal.dao.NewActivityAwardLogDao;
import com.qdlc.p2p.dal.dto.AdditionalMovieTicketRule;
import com.qdlc.p2p.dal.dto.AdditionalUserMovieTicket;
import com.qdlc.p2p.dal.dto.NewActivityAwardLog;
import com.qdlc.p2p.dal.dto.User;
import com.qdlc.p2p.dal.model.AdditionalUserMovieTicketModel;
import com.qdlc.p2p.dal.model.BaseGiveAwardModel;

/**
 * Created by liaoxiangkai on 2015/11/24.
 */
@Service("giveUserMovieTicketService")
public class GiveUserMovieTicketServiceImpl implements BaseGiveAwardService {
    @Resource
    private AdditionalUserMovieTicketDao additionalUserMovieTicketDao;

    @Resource
    private AdditionalMovieTicketRuleDao additionalMovieTicketRuleDao;

    @Resource
    private NewActivityAwardLogDao newActivityAwardLogDao;

    @Override
    public void giveAward(BaseGiveAwardModel baseGiveAwardModel) {
        User user = baseGiveAwardModel.getUser();
        if (null == user || user.getUserId() < 0) return;
        //同一个电影最多送两张电影票
        int sameMovieCount = additionalUserMovieTicketDao.getUserSameMovieCount(user.getUserId(), baseGiveAwardModel.getRuleId());
        if (sameMovieCount >= 2) return;
        AdditionalMovieTicketRule additionalMovieTicketRule = additionalMovieTicketRuleDao.find(baseGiveAwardModel.getRuleId());
        // 判断规则存在.判断状态 0:启用 1:未启用
        if (additionalMovieTicketRule == null || additionalMovieTicketRule.getStatus() != 0) return;
        int count = additionalMovieTicketRule.getCount();
        //保存赠送用户的电影票信息
        AdditionalUserMovieTicket additionalUserMovieTicket = new AdditionalUserMovieTicket();
        Date startTime = DateUtil.getNow();
        String orderNo = OrderNoUtil.getInstance().getSerialNumber(); //请求php流水号
        additionalUserMovieTicket.setExpiredTime(additionalMovieTicketRule.getExpiredTime());
        additionalUserMovieTicket.setUser(user);
        additionalUserMovieTicket.setAdditionalMovieTicketRule(additionalMovieTicketRule);
        additionalUserMovieTicket.setCount(count);
        additionalUserMovieTicket.setStatus(AdditionalUserMovieTicketModel.USER_MOVIETICKE_REQUEST);//前往请求php接口/请求接口失败
        additionalUserMovieTicket.setOrderNo(orderNo);
        additionalUserMovieTicket.setSourceType(baseGiveAwardModel.getSourceType());
        additionalUserMovieTicket.setAddTime(startTime);

        try {
            //访问php接口，给用户出票 参数：channel_id,sign(channel_title，channel_id，create_time，channel_key),orderNo,userid,mobile
            NameValuePair[] data = {new NameValuePair("mobile", user.getMobilePhone()), new NameValuePair("orderNo", orderNo),
                    new NameValuePair("userid", String.valueOf(user.getUserId()))};
            String url = SystemConfigHelper.getValue(SystemConfigHelper.Nid.REQUEST_PHP_DOMAIN) + "/Film/index.html";
            String result = AdditionalUserMovieTicketModel.requestPHP(url, data);
            //如果请求返回成功代码0，则更改状态为等待出票，否则还需请求
            if ("0".equals(JSONObject.parseObject(result).get("code")))
                additionalUserMovieTicket.setStatus(AdditionalUserMovieTicketModel.USER_MOVIETICKE_WAIT);
        } catch (Exception e) {
            e.printStackTrace();
        }

        additionalUserMovieTicket = additionalUserMovieTicketDao.save(additionalUserMovieTicket);
        if (additionalUserMovieTicket != null) {
            //活动赠与活动记录
            NewActivityAwardLog newActivityAwardLog = new NewActivityAwardLog();
            newActivityAwardLog.setUser(user);
            newActivityAwardLog.setTache(baseGiveAwardModel.getSourceType());
            newActivityAwardLog.setRuleType(baseGiveAwardModel.getRuleType());
            newActivityAwardLog.setRuleId(baseGiveAwardModel.getRuleId());
            newActivityAwardLog.setCount(count);
            newActivityAwardLog.setAddTime(startTime);
            newActivityAwardLogDao.save(newActivityAwardLog);
        }
    }

    /**
     * 发放给一个用户兑换券
     *  参数：user用户, count数量， sourceType来源， validDay有效天数，
     * @param baseGiveAwardModel
     */
    @Override
    public void giveSingleUserAward(BaseGiveAwardModel baseGiveAwardModel) {
        AdditionalUserMovieTicket additionalUserMovieTicket = new AdditionalUserMovieTicket();
        User user = baseGiveAwardModel.getUser();
        String orderNo = OrderNoUtil.getInstance().getSerialNumber(); //请求php流水号
        additionalUserMovieTicket.setAddTime(DateUtil.getNow());
        additionalUserMovieTicket.setUser(user);
        additionalUserMovieTicket.setCount(((Double)baseGiveAwardModel.getAmount()).intValue()); //设置数量
        additionalUserMovieTicket.setExpiredTime(DateUtil.rollDay(new Date(), 60)); //TODO 兑换券的有效期
        additionalUserMovieTicket.setSourceType(baseGiveAwardModel.getSourceType());
        additionalUserMovieTicket.setOrderNo(orderNo);
        additionalUserMovieTicket.setStatus(AdditionalUserMovieTicketModel.USER_MOVIETICKE_REQUEST);//前往请求php接口或请求接口失败

        try {
            //访问php接口，给用户出票 参数：channel_id,sign(channel_title，channel_id，create_time，channel_key),orderNo,userid,mobile
            NameValuePair[] data = {new NameValuePair("mobile", user.getMobilePhone()), new NameValuePair("orderNo", orderNo),
                    new NameValuePair("userid", String.valueOf(user.getUserId()))};
            String url = SystemConfigHelper.getValue(SystemConfigHelper.Nid.REQUEST_PHP_DOMAIN) + "/Film/index.html";
            String result = AdditionalUserMovieTicketModel.requestPHP(url, data);
            //如果请求返回成功代码0，则更改状态为等待出票，否则还需请求
            if ("0".equals(JSONObject.parseObject(result).get("code")))
                additionalUserMovieTicket.setStatus(AdditionalUserMovieTicketModel.USER_MOVIETICKE_WAIT);
        } catch (Exception e) {
            e.printStackTrace();
        }
        additionalUserMovieTicket  = additionalUserMovieTicketDao.save(additionalUserMovieTicket);
        if (null != additionalUserMovieTicket) {
            NewActivityAwardLog newActivityAwardLog = new NewActivityAwardLog(baseGiveAwardModel.getUser(), baseGiveAwardModel.getSourceType(),baseGiveAwardModel.getAmount(), BaseGiveAwardModel.RULE_TYPE_MOVIETICKET);
            newActivityAwardLogDao.save(newActivityAwardLog);
        }
    }
}
